package org.jac.hib_test.dao;

import org.hibernate.Query;
import org.jac.hib_test.entity.UserEntity;
import org.jac.hibernate.HibernateUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by JAC.
 * Date: 14-4-1
 * Time: 下午3:05
 */
public class UserDao {
    public static void add(UserEntity user){
        HibernateUtil.add(user);
    }
    public static void update(UserEntity user){
        HibernateUtil.update(user);
    }

    /**
     * 用户分页查询，页码从1开始
     * @param pageIndex 页码
     * @param pageMax 一页多少条
     * @return
     */
    public static List<UserEntity> pagingList(int pageIndex,int pageMax){
        String hql = "from UserEntity as u ";
        Query query = HibernateUtil.getSession().createQuery(hql);;
        query.setFirstResult((pageIndex-1)*pageMax);
        query.setMaxResults(pageIndex*pageMax);
        List list = query.list();
        List<UserEntity> uList = new ArrayList<UserEntity>();
        for (Object o : query.list()) {
            uList.add((UserEntity) o);
        }
        return uList;
    }
    public static void main(String[] args) {
//        for (int i = 1; i < 20; i++) {
//            UserEntity user = new UserEntity();
//            user.setId(i);
//            user.setName("用户"+i);
//            UserDao.update(user);
//            System.out.println("id:"+user.getId()+" name:"+user.getName());
//        }


        String hql = "SELECT COUNT(*) From UserEntity as u ";
        Query query = HibernateUtil.getSession().createQuery(hql);
//        query.setString("id","2");
        query.setFirstResult(0);
        query.setMaxResults(10);
        System.out.println(query.uniqueResult());

//        List<UserEntity> ulist = (List<UserEntity>)query.list();
//        for (Object o : ulist) {
//            UserEntity user = (UserEntity) o;
//            System.out.println("id:"+user.getId()+" name:"+user.getName());
//        }
//        List<UserEntity> ulist = HibernateUtil.queryToPaging(hql,2,5,2);
//        for (UserEntity user : ulist) {
//            System.out.println("id:"+user.getId()+" name:"+user.getName());
//        }
//        UserEntity user = new UserEntity();
//        user.setName("用户17");
//        UserDao.add(user);
//        System.out.println("id:"+user.getId()+" name:"+user.getName());
        //UserEntity user = (UserEntity) query.uniqueResult();
        //System.out.println("id:"+user.getId()+" name:"+user.getName());
    }
}
